package com.xql.framework.listener;

import com.xql.framework.action.ActionFactory;
import com.xql.framework.action.ActionMapping;
import com.xql.framework.action.ActionSupport;
import com.xql.framework.util.ReadXML;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * Created by apple on 15/3/22.
 */
public class XqlFrameworkListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("xqlframework 启动.....");
        ServletContext context = servletContextEvent.getServletContext();
        String tomcatPath = context.getRealPath("/");
        String xmlPath = context.getInitParameter("xqlmvc");
        String path = context.getContextPath();
       // System.out.println("path==="+path);
        Map<String,ActionMapping> actionMap = ReadXML.getElements(tomcatPath+xmlPath);
        ActionFactory.init(actionMap);
        createActions(actionMap);
        System.out.println("web Application setup is success !");
        System.out.println("系统加载并启动成功！");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("系统注销中。。。。。。");
    }

    /**
     * builder actionMappingMap
     * @param actionMappingMap
     */
    public static  void createActions(Map<String,ActionMapping> actionMappingMap){
        Set<String> keySet = actionMappingMap.keySet();
        for(String key:keySet){
            ActionMapping actionMapping = actionMappingMap.get(key);
            try {
                Class clazz = Class.forName(actionMapping.getActionClass());

                Object obj = (ActionSupport) clazz.newInstance();
                ActionFactory.add(key, obj);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
